<template>
  <div class="app-container">
    <el-card shadow="never">
      <div slot="header" class="clearfix">
        <span>自动组卷</span>
        <el-button
          style="float: right"
          type="primary"
          :loading="generating"
          @click="handleGenerate"
        >开始组卷
        </el-button>
      </div>

      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="试卷标题" prop="title">
              <el-input v-model="form.title" placeholder="请输入试卷标题"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="试卷编码" prop="code">
              <el-input v-model="form.code" placeholder="请输入试卷编码"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="组卷方式">
          <el-radio-group v-model="form.useGenetic">
            <el-radio :label="false">固定系数组卷</el-radio>
            <el-radio :label="true">策略组卷</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 固定系数组卷配置 -->
        <div v-if="!form.useGenetic">
          <el-form-item label="组卷模板" prop="templateId">
            <el-select
              v-model="form.templateId"
              placeholder="请选择组卷模板"
              style="width: 100%"
              @change="handleTemplateChange"
            >
              <el-option
                v-for="item in templateOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>

          <el-card shadow="never" class="template-preview">
            <div slot="header" class="clearfix">
              <span>模板预览</span>
            </div>
            <div v-if="currentTemplate">
              <p><strong>模板名称：</strong>{{ currentTemplate.name }}</p>
              <p><strong>模板描述：</strong>{{ currentTemplate.description }}</p>
              <p><strong>题目总数：</strong>{{ currentTemplate.questionCount }}</p>
              <p><strong>试卷总分：</strong>{{ currentTemplate.totalScore }}</p>

              <el-divider></el-divider>

              <h4>题型配置</h4>
              <el-table :data="currentTemplateTypeConfig" border style="width: 100%">
                <el-table-column prop="name" label="题型" width="180"/>
                <el-table-column prop="count" label="数量" width="80"/>
                <el-table-column prop="score" label="每题分数"/>
              </el-table>
            </div>
            <div v-else class="empty-tip">
              请选择组卷模板
            </div>
          </el-card>
        </div>

        <!-- 遗传算法组卷配置 -->
        <div v-else>
          <el-form-item label="组卷策略" prop="strategyId">
            <el-select
              v-model="form.strategyId"
              placeholder="请选择组卷策略"
              style="width: 100%"
              @change="handleStrategyChange"
            >
              <el-option
                v-for="item in strategyOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>

          <el-card shadow="never" class="strategy-preview">
            <div slot="header" class="clearfix">
              <span>策略预览</span>
            </div>
            <div v-if="currentStrategy">
              <p><strong>策略名称：</strong>{{ currentStrategy.name }}</p>
              <p><strong>策略描述：</strong>{{ currentStrategy.description }}</p>
              <p><strong>策略类型：</strong>{{ currentStrategy.strategyType === 1 ? '智能组卷' : '标准模板' }}</p>

              <el-divider></el-divider>

              <h4>难度配置</h4>
              <el-table :data="currentStrategyDifficultyConfig" border style="width: 100%">
                <el-table-column prop="level" label="难度等级" width="120"/>
                <el-table-column prop="ratio" label="占比(%)"/>
              </el-table>

              <el-divider></el-divider>

              <h4>题型配置</h4>
              <el-table :data="currentStrategyQuestionConfig" border style="width: 100%">
                <el-table-column prop="name" label="题型" width="180"/>
                <el-table-column prop="count" label="数量" width="80"/>
                <el-table-column prop="score" label="每题分数"/>
              </el-table>

              <el-divider v-if="currentStrategyKnowledgeConfig.length > 0"></el-divider>

              <div v-if="currentStrategyKnowledgeConfig.length > 0">
                <h4>知识点配置</h4>
                <el-tag
                  v-for="item in currentStrategyKnowledgeConfig"
                  :key="item"
                  type="info"
                  class="knowledge-tag"
                >{{ item }}</el-tag>
              </div>

              <el-divider></el-divider>

              <h4>遗传算法参数</h4>
              <el-form :model="form.geneticConfig" label-width="150px">
                <el-form-item label="种群大小">
                  <el-input-number v-model="form.geneticConfig.populationSize" :min="20" :max="200"/>
                </el-form-item>
                <el-form-item label="最大迭代次数">
                  <el-input-number v-model="form.geneticConfig.maxGenerations" :min="10" :max="500"/>
                </el-form-item>
                <el-form-item label="交叉概率">
                  <el-slider v-model="form.geneticConfig.crossoverRate" :min="0.1" :max="1" :step="0.05"/>
                </el-form-item>
                <el-form-item label="变异概率">
                  <el-slider v-model="form.geneticConfig.mutationRate" :min="0.01" :max="0.5" :step="0.01"/>
                </el-form-item>
                <el-form-item label="适应度阈值">
                  <el-slider v-model="form.geneticConfig.fitnessThreshold" :min="0.5" :max="1" :step="0.05"/>
                </el-form-item>
                <el-form-item label="时间限制(秒)">
                  <el-input-number v-model="form.geneticConfig.timeLimit" :min="10" :max="300"/>
                </el-form-item>
                <el-form-item label="降级为模板组卷">
                  <el-switch v-model="form.geneticConfig.fallbackToTemplate"/>
                </el-form-item>
              </el-form>
            </div>
            <div v-else class="empty-tip">
              请选择组卷策略
            </div>
          </el-card>
        </div>
      </el-form>
    </el-card>

    <!-- 组卷结果对话框 -->
    <el-dialog
      :title="resultDialog.title"
      :visible.sync="resultDialog.visible"
      width="60%"
      :close-on-click-modal="false"
    >
      <div v-if="resultDialog.success">
        <el-alert
          :title="`组卷成功！${resultDialog.message}`"
          type="success"
          show-icon
          :closable="false"
        />

        <el-divider></el-divider>

        <div v-if="resultDialog.isGenetic" class="genetic-result">
          <el-row :gutter="20">
            <el-col :span="8">
              <div class="result-item">
                <div class="result-label">迭代次数</div>
                <div class="result-value">{{ resultDialog.generation }}</div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="result-item">
                <div class="result-label">适应度</div>
                <div class="result-value">{{ resultDialog.fitness.toFixed(2) }}</div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="result-item">
                <div class="result-label">耗时</div>
                <div class="result-value">{{ resultDialog.timeCost }}ms</div>
              </div>
            </el-col>
          </el-row>
        </div>

        <el-divider></el-divider>

        <div class="action-buttons">
          <el-button
            type="primary"
            @click="handleViewPaper"
          >查看试卷</el-button>
          <el-button
            type="success"
            @click="handlePreviewPaper"
          >预览试卷</el-button>
          <el-button
            @click="resultDialog.visible = false"
          >关闭</el-button>
        </div>
      </div>
      <div v-else>
        <el-alert
          :title="`组卷失败！${resultDialog.message}`"
          type="error"
          show-icon
          :closable="false"
        />

        <div v-if="form.useGenetic && form.geneticConfig.fallbackToTemplate" class="fallback-suggestion">
          <el-divider></el-divider>
          <p>是否尝试使用固定系数组卷？</p>
          <el-button
            type="primary"
            @click="handleFallbackToTemplate"
          >降级为模板组卷</el-button>
        </div>

        <div class="action-buttons">
          <el-button
            @click="resultDialog.visible = false"
          >关闭</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { autoGeneratePaper, templateGenerate, geneticGenerate, listStrategy, listTemplate, pageTemplate } from '@/api/paper2/generate'

export default {
  name: 'PaperAutoGenerate',
  data() {
    return {
      form: {
        title: '',
        code: '',
        useGenetic: false,
        templateId: null,
        strategyId: null,
        geneticConfig: {
          populationSize: 50,
          maxGenerations: 100,
          crossoverRate: 0.8,
          mutationRate: 0.1,
          fitnessThreshold: 0.95,
          timeLimit: 30,
          fallbackToTemplate: true
        }
      },
      rules: {
        title: [{ required: true, message: '请输入试卷标题', trigger: 'blur' }],
        code: [{ required: true, message: '请输入试卷编码', trigger: 'blur' }],
        templateId: [{ required: true, message: '请选择组卷模板', trigger: 'change' }],
        strategyId: [{ required: true, message: '请选择组卷策略', trigger: 'change' }]
      },
      templateOptions: [],
      strategyOptions: [],
      currentTemplate: null,
      currentStrategy: null,
      generating: false,
      resultDialog: {
        visible: false,
        title: '组卷结果',
        success: false,
        message: '',
        isGenetic: false,
        generation: 0,
        fitness: 0,
        timeCost: 0,
        paperId: null
      }
    }
  },
  computed: {
    currentTemplateTypeConfig() {
      if (!this.currentTemplate || !this.currentTemplate.configJson) return []
      try {
        const config = JSON.parse(this.currentTemplate.configJson)
        return config.types || []
      } catch (e) {
        return []
      }
    },
    currentStrategyDifficultyConfig() {
      if (!this.currentStrategy || !this.currentStrategy.difficultyConfig) return []
      try {
        const config = JSON.parse(this.currentStrategy.difficultyConfig)
        return Object.entries(config)
          .filter(([key]) => key.startsWith('difficulty_'))
          .map(([key, value]) => ({
            level: this.getDifficultyText(parseInt(key.substring(11))),
            ratio: (value * 100).toFixed(1)
          }))
      } catch (e) {
        return []
      }
    },
    currentStrategyQuestionConfig() {
      if (!this.currentStrategy || !this.currentStrategy.questionConfig) return []
      try {
        const config = JSON.parse(this.currentStrategy.questionConfig)
        return config.types || []
      } catch (e) {
        return []
      }
    },
    currentStrategyKnowledgeConfig() {
      if (!this.currentStrategy || !this.currentStrategy.knowledgeConfig) return []
      try {
        const config = JSON.parse(this.currentStrategy.knowledgeConfig)
        if (Array.isArray(config.knowledgeNames)) {
          return config.knowledgeNames
          // return config.knowledgePoints
        }
        return []
      } catch (e) {
        return []
      }
    }
  },
  created() {
    this.loadTemplates()
    this.loadStrategies()
  },
  methods: {
    loadTemplates() {
      pageTemplate({ pageSize: 1000 }).then(response => {
        this.templateOptions = response.rows
      })
    },
    loadStrategies() {
      listStrategy({ pageSize: 1000 }).then(response => {
        this.strategyOptions = response.rows
      })
    },
    handleTemplateChange(templateId) {
      this.currentTemplate = this.templateOptions.find(t => t.id === templateId) || null
    },
    handleStrategyChange(strategyId) {
      this.currentStrategy = this.strategyOptions.find(s => s.id === strategyId) || null

      // 如果选择了策略，加载默认的遗传算法配置
      if (this.currentStrategy) {
        this.form.geneticConfig = {
          populationSize: this.currentStrategy.populationSize || 50,
          maxGenerations: this.currentStrategy.maxGenerations || 100,
          crossoverRate: this.currentStrategy.crossoverRate || 0.8,
          mutationRate: this.currentStrategy.mutationRate || 0.1,
          fitnessThreshold: this.currentStrategy.fitnessThreshold || 0.95,
          timeLimit: this.currentStrategy.timeLimit || 30,
          fallbackToTemplate: true
        }
      }
    },
    handleGenerate() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.generating = true

          const request = {
            title: this.form.title,
            code: this.form.code,
            useGenetic: this.form.useGenetic,
            templateId: this.form.templateId,
            strategyId: this.form.strategyId,
            geneticConfig: this.form.useGenetic ? this.form.geneticConfig : null
          }

          const generateFn = this.form.useGenetic ? geneticGenerate : templateGenerate

          generateFn(request).then(response => {
            const data = response.data;
            this.resultDialog.success = data.success
            this.resultDialog.message = data.message
            this.resultDialog.isGenetic = this.form.useGenetic
            this.resultDialog.generation = data.generation || 0
            this.resultDialog.fitness = data.fitness || 0
            this.resultDialog.timeCost = data.timeCost || 0
            this.resultDialog.paperId = data.paperId || null
            this.resultDialog.visible = true
          }).catch(error => {
            this.$message.error('组卷失败: ' + error.message)
          }).finally(() => {
            this.generating = false
          })
        }
      })
    },
    handleViewPaper() {
      if (this.resultDialog.paperId) {
        this.$router.push(`/paper2/manual?id=${this.resultDialog.paperId}`)
      }
      this.resultDialog.visible = false
    },
    handlePreviewPaper() {
      if (this.resultDialog.paperId) {
        const routeData = this.$router.resolve({
          path: '/paper2/preview',
          query: { id: this.resultDialog.paperId }
        })
        window.open(routeData.href, '_blank')
      }
      this.resultDialog.visible = false
    },
    handleFallbackToTemplate() {
      this.form.useGenetic = false
      this.resultDialog.visible = false
      this.$nextTick(() => {
        this.$message.info('已切换为固定系数组卷模式，请选择模板后重新组卷')
      })
    },
    getDifficultyText(level) {
      switch (level) {
        case 1: return '容易'
        case 2: return '偏易'
        case 3: return '中等'
        case 4: return '偏难'
        case 5: return '困难'
        default: return '未知'
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.template-preview, .strategy-preview {
  margin-top: 20px;

  .empty-tip {
    color: #999;
    text-align: center;
    padding: 20px;
  }
}

.knowledge-tag {
  margin-right: 8px;
  margin-bottom: 8px;
}

.genetic-result {
  .result-item {
    text-align: center;
    padding: 10px;

    .result-label {
      font-size: 14px;
      color: #666;
      margin-bottom: 5px;
    }

    .result-value {
      font-size: 24px;
      font-weight: bold;
      color: #409EFF;
    }
  }
}

.fallback-suggestion {
  text-align: center;
  margin-top: 20px;
}

.action-buttons {
  text-align: center;
  margin-top: 20px;
}
</style>
